package com.sebscape.sebcms.tools;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;

/**
 * User: sbelt
 * Date: Sep 23, 2005
 * Time: 10:24:37 PM
 */
public class FileUploadManager {

    private static Log log = LogFactory.getLog(FileUploadManager.class);

    /**
     * Returns a map of File objects, one for every uploaded file in
     * the (Multipart)Request, such that the key is the input Name and the value
     * is the file.
     *
     *
     * @param request
     * @return Map of File Objects.
     */
    public Map<String, Object> extractFileMap(HttpServletRequest request) {
        if (!(request instanceof MultiPartRequestWrapper)) {
            throw new RuntimeException("Request was not a MultipartRequest, could not extract files.");
        }
        MultiPartRequestWrapper multiWrapper =
                (MultiPartRequestWrapper) request;
        List<String> actionErrors = new ArrayList<String>();
        if (multiWrapper.hasErrors()) {
            actionErrors.addAll( multiWrapper.getErrors() );
        }

        Enumeration<String> e = multiWrapper.getFileParameterNames();
        Map<String, Object> files = new LinkedHashMap<String, Object>();
        while (e != null && e.hasMoreElements()) {
            // get the value of this input tagname
            String inputTag = (String) e.nextElement();
            log.debug("inputTage = " + inputTag );
            // get the file(s) using the tagName
            File[] fileArray = multiWrapper.getFiles( inputTag );
            log.debug("fileArray[] = " + fileArray );
            // loop thru any File Objects in the array and add them to the map.
            for( int i = 0; fileArray != null && i < fileArray.length; i++ ){
                // If it's null the upload failed
                if ( fileArray[ i ] == null ) {
                    actionErrors.add("fileArray[ " + i + " ] is null" );
                } else {
                    // If multiple inputs use the same name-attribute, we only use the first file.
                    if( !files.containsKey( inputTag )){
                        files.put( inputTag, fileArray[ i ] );
                        log.debug("added to map: " + inputTag + " / " + fileArray[ i ].getName() );
                    }
                }
            }
        }
        if (actionErrors.isEmpty()) {
            log.info("No errors, returning file list.");
        } else {
            if (log.isDebugEnabled()) {
                log.error("Exceptions found. " + actionErrors);
            }
            files.put( "EXCEPTIONS", actionErrors );
            //throw exceptionBag;
        }
        return files;
    }

    
/*    public static Blob convertToBlob(File file, final String fieldName) throws Exception {
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(file));
            // This should close input stream when done with it.
            return Hibernate.createBlob(in);

        } catch (IOException e) {
            log.error("Failed to saved", e);
            throw new RuntimeException("Failed to convert " + fieldName + " to blob");
        }
    }

*/

}
